package by.bsu.rfe.belianko.euniversity.controller.command;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.constants.LoggerMessages;
import by.bsu.rfe.belianko.euniversity.constants.PageNames;
import by.bsu.rfe.belianko.euniversity.dao.IStudentsDAO;
import by.bsu.rfe.belianko.euniversity.exceptions.CommandException;
import by.bsu.rfe.belianko.euniversity.exceptions.DaoTechnicalException;
import by.bsu.rfe.belianko.euniversity.model.DataBaseLayer;
import by.bsu.rfe.belianko.euniversity.model.Student;

/**
 * Saves a user in the database.
 * 
 * @author Vitali_Belianko
 * 
 */
public class SaveCommand implements Command {
	private static final String CAN_NOT_SAVE_STUDENTS_IN_DB = "Can not save students in DB!";
	private static final String CAN_NOT_GET_STUDENT_BY_LOGIN = "Can not get student by login!";
	private static final String ERROR_MESSAGE = "errorMessage";
	private static final String STUDENT = "student";
	private static final String NAME = "name";
	private static final String PASSWORD = "password";
	private static final String LOGIN = "login";
	private static final IStudentsDAO studentsDao = DataBaseLayer.getStudentsDao();
	private static final Logger LOGGER = Logger.getLogger(SaveCommand.class);

	/**
	 * Performs registration of the user in the system.
	 * 
	 * @param request
	 * 
	 * @return cabinet page, or register page if error message not null
	 * @throws CommandException
	 */
	@Override
	public String execute(HttpServletRequest request) throws CommandException {

		LOGGER.debug(LoggerMessages.STARTED_COMMAND);

		Student student = new Student();
		String login = request.getParameter(LOGIN);
		String password = request.getParameter(PASSWORD);
		String name = request.getParameter(NAME);
		student.setLogin(login);
		student.setPassword(password);
		student.setName(name);

		String errorMessage = null;
		try {
			errorMessage = studentsDao.saveStudent(student);
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(CAN_NOT_SAVE_STUDENTS_IN_DB, e);
		}
		if (errorMessage == null) {

			try {
				student = studentsDao.getStudentByLogin(login);
			} catch (DaoTechnicalException e) {
				LOGGER.error(e.getMessage());
				throw new CommandException(CAN_NOT_GET_STUDENT_BY_LOGIN, e);
			}

			request.getSession(true).setAttribute(STUDENT, student);
			return PageNames.CABINET_PAGE;
		} else {
			request.setAttribute(ERROR_MESSAGE, errorMessage);
			LOGGER.debug(LoggerMessages.FINISHED_COMMAND);
			return PageNames.REGISTER_PAGE;
		}

	}

}
